package com.zy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.domain.SysUser;
import com.zy.domain.SysUserRole;
import com.zy.mapper.SysUserRoleMapper;
import com.zy.service.SysUserRoleService;
import com.zy.service.SysUserService;
import com.zy.mapper.SysUserMapper;
import com.zy.util.AuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author RASH_ZY
 * @description 针对表【sys_user(系统用户)】的数据库操作Service实现
 * @createDate 2025-03-29 23:22:50
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 新增管理员
     * 1.新增管理员
     * 2.新增管理员与角色的关系
     *
     * @param sysUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveSysUser(SysUser sysUser) {
        //封装新增管理员信息
        sysUser.setCreateUserId(AuthUtils.getLoginUserId());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(1L);
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        //新增管理员
        int insert = sysUserMapper.insert(sysUser);
        //新增管理员成功，执行新增管理员的角色关系操作
        if (insert > 0) {
            //获取新增管理员的id：userId
            Long userId = sysUser.getUserId();
            //获取管理员的角色id集合：roleIdList
            //该集合由前端新增管理员时勾选对应的框传递而来，可能勾选多个，使用集合接收
            List<Long> roleIdList = sysUser.getRoleIdList();
            if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() != 0) {
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                roleIdList.forEach(roleId -> {
                    //封装管理员与角色关系 userIDd+roleId
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(userId);
                    sysUserRole.setRoleId(roleId);
                    /*//新增管理员与角色的关系，不建议在循环中执行SQL语句
                    通过定义一个集合，批量添加解决
                    sysUserRoleMapper.insert(sysUserRole);*/
                    sysUserRoleList.add(sysUserRole);
                });
                //批量添加管理员与角色关系
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return insert;
    }

    /**
     * 根据标识id查询系统管理员信息
     * @param id
     * @return
     */
    @Override
    public SysUser querySysUserInfoByUserId(Long id) {
        //根据标识id查询系统管理员信息
        SysUser sysUser = sysUserMapper.selectById(id);
        //根据标识id查询管理员与角色的关系集合
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, id)
        );
        //判断是否有值
        if (CollectionUtil.isNotEmpty(sysUserRoleList) && sysUserRoleList.size() != 0) {
            //获取管理员的角色id集合
            List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            //将角色id集合封装到管理员信息中
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }

    /**
     * 修改管理员信息
     *  1.删除原有的管理员与角色关系
     *  2.添加新的管理员与角色关系
     *  3.修改管理员的基本信息
     * @param sysUser
     * @return
     */
    @Override
    public Integer modifySysUserInfo(SysUser sysUser) {
        //获取当前正在修改的管理员的id
        Long userId = sysUser.getUserId();
        //1.删除原有的管理员与角色关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId));

        //2.添加新的管理员与角色关系
        //获取管理员的角色id集合：roleIdList
        //该集合由前端新增管理员时勾选对应的框传递而来，可能勾选多个，使用集合接收
        List<Long> roleIdList = sysUser.getRoleIdList();
        if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() != 0) {
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            roleIdList.forEach(roleId -> {
                //封装管理员与角色关系 userIDd+roleId
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                    /*//新增管理员与角色的关系，不建议在循环中执行SQL语句
                    通过定义一个集合，批量添加解决
                    sysUserRoleMapper.insert(sysUserRole);*/
                sysUserRoleList.add(sysUserRole);
            });
            //批量添加管理员与角色关系
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        //3.修改管理员的基本信息
        //判是否修改了密码
        String newPassword = sysUser.getPassword();
        if (StringUtils.hasText(newPassword)) {
            //前端传来的password有值，代表需要修改密码。进行加密
            sysUser.setPassword(bCryptPasswordEncoder.encode(newPassword));
        }
        return sysUserMapper.updateById(sysUser);
    }

    /**
     * 批量/单个删除管理员
     *  1.批量/单个删除管理员与角色关系
     *  2.批量/单个删除管理员
     * @param userIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeSysUserListByUserIds(List<Long> userIds) {
        //1.批量/单个删除管理员与角色关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId, userIds)
        );
        //2.批量/单个删除管理员
        //删除成功的标志：删除的条目数 = userIds的个数
        return sysUserMapper.deleteBatchIds(userIds) == userIds.size();
    }

}




